<?php
class Controller_Setting_Basic extends Controller_Abstract
{
	function actionCurrencyList()
	{
		$this->_view['title'] = '币种列表';
		$currency = Currency::find()->asArray()->getAll();
		$this->_view['currency'] = $currency;
	}
	
	function actionCurrencyEditSave()
	{
		$this->_view['title'] = '修改币种（保存）';
		$currency_id = $_REQUEST['currency_id'];
		$rate = $_REQUEST['rate'];
		$currency = Currency::find('id=?', $currency_id)->asArray()->getOne();
		if ($currency)
		{
			QDB::getConn()->execute('update currency set rate=\'' . $rate . '\' where id=' . $currency_id);
			echo 1;exit;
		}
	}
	
	function actionShopList()
	{
		$this->_view['title'] = '网店列表';
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 0;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 20;
		$condition = Helper_BSS_Normal::buildCondition();
		$platform = array('DAVIDSONNE', 'Orr', 'IAINSWAN', 'robertaspland', 'NNJYCE', 'shariwilliams', 'TODD', 'ebay', 'wish', 'aliexpress');
		$this->_view['platform'] = $platform;
		$condition['sel_platform'] = 1;
		$result = Shop::search($condition, $cp, $ps);
		if ($result['ack'] == SUCCESS)
		{
			$page = new Helper_BSS_Page($result['pagination'], url('Setting::Basic/ShopList', $condition));
			$this->_view['page'] = $page->getPage();
			$this->_view['shop'] = $result['data'];
		}
	}
	
	function actionShopCreateSave()
	{
		$this->_view['title'] = '新建网店（保存）';
		if ($this->_context->isPOST())
		{
			$shop = Shop::find('name=? and platform=?', $_POST['name'], $_POST['platform'])->asArray()->getOne();
			if ($shop)
			{
				return $this->_redirectMessage('创建失败', '已存在该店铺/网站', url('Setting::Basic/ShopList'), FAILURE);
			}
			else
			{
				$shop = new Shop();
				$shop->name = $_POST['name'];
				$shop->platform = $_POST['platform'];
				$shop->status = $_POST['status'];
				$shop->save();
				return $this->_redirectMessage('创建成功', '正在返回..', url('Setting::Basic/ShopList'), SUCCESS);
			}
		}
	}
	
	function actionEbayTokenList()
	{
		$this->_view['title'] = 'Ebay令牌';
		$shop = Shop_User_Mapping::getShopByPlatform('ebay');
		foreach ($shop as $key => $s)
		{
			$api = Shop_API_Ebay::find('shop_id=?', $s['id'])->asArray()->getOne();
			$shop[$key]['expire_time'] = $api ? $api['expire_time'] : '';
			$shop[$key]['token'] = $api ? $api['token'] : '';
		}
		$this->_view['shop'] = $shop;
	}
	
	function actionEbayTokenCreate()
	{
		$this->_view['title'] = '获取SessionID';
		$header = array(
			'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
			'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
			'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
			'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
			'X-EBAY-API-SITEID:0',
			'X-EBAY-API-CALL-NAME:GetSessionID'
		);
		$xml = '<?xml version="1.0" encoding="utf-8"?>';
		$xml .= '<GetSessionIDRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
		$xml .= '<RuName>' . Q::ini('custom_api/ebay_app_runame') . '</RuName>';
		$xml .= '</GetSessionIDRequest>​';
		$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'GetSessionID');
		if ($result['ack'] == SUCCESS)
		{
			$response = simplexml_load_string($result['data']);
			if ($response->Ack[0] == 'Success');
			{
				$url = "https://signin.ebay.com/ws/eBayISAPI.dll?SignIn&RuName=" . urlencode(Q::ini('custom_api/ebay_app_runame')) . "&SessID=" . urlencode($response->SessionID[0]);
				$this->_view['url'] = $url;
				$this->_view['shop_id'] = $_GET['shop_id'];
				$this->_view['session_id'] = $response->SessionID[0];
			}
		}
	}
	
	function actionEbayTokenCreateSave()
	{
		$this->_view['title'] = '获取token';
		$header = array(
			'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
			'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
			'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
			'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
			'X-EBAY-API-SITEID:0',
			'X-EBAY-API-CALL-NAME:FetchToken'
		);
		$xml = '<?xml version="1.0" encoding="utf-8"?>';
		$xml .= '<FetchTokenRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
		$xml .= '<SessionID>' . $_POST['session_id'] . '</SessionID>';
		$xml .= '</FetchTokenRequest>';
		$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'FetchToken');
		if ($result['ack'] == SUCCESS)
		{
			$response = simplexml_load_string($result['data']);
			if ($response->Ack[0] == 'Success')
			{
				$token = Shop_API_Ebay::find('shop_id=?', $_POST['shop_id'])->getOne();
				if (!$token['id'])
				{
					$token = new Shop_API_Ebay();
					$token->shop_id = $_POST['shop_id'];
				}
				$token->token = $response->eBayAuthToken[0];
				$token->expire_time = date('Y-m-d H:i:s', strtotime($response->HardExpirationTime[0]));
				$token->save();
				return $this->_redirect(url('Setting::Basic/EbayTokenList'));
			}
		}
		else
		{
			return $this->_redirectMessage('失败', $result['message'], url('Setting::Basic/EbayTokenList'), FAILURE);
		}
	}
	
	function actionAmazonTokenList()
	{
		$this->_view['title'] = 'Amazon令牌';
		$condition = Helper_BSS_Normal::buildCondition();
		$condition['status'] = Q::ini('custom_flag/shop_status/enabled/value');
		$where = Shop_Api_Amazon::buildSearchWhere($condition);
		$where .= ' and (shop.platform=\'DAVIDSONNE\' or shop.platform=\'Orr\' or shop.platform=\'IAINSWAN\' or shop.platform=\'robertaspland\' or shop.platform=\'NNJYCE\' or shop.platform=\'shariwilliams\' or shop.platform=\'TODD\')';
		$shop = Shop::find($where)
			->joinLeft('shop_api_amazon', '', 'shop_api_amazon.shop_id=shop.id')
			->setColumns('shop_api_amazon.*, shop.id as shop_id, shop.name, shop.platform')
			->asArray()->getAll();
		$this->_view['shop'] = $shop;
	}
	
	function actionAmazonTokenEdit()
	{
		$this->_view['title'] = 'Amazon令牌修改';
		if ($_GET['shop_id'])
		{
			$shop = Shop::find('shop.id=?', $_GET['shop_id'])
				->joinLeft('shop_api_amazon', '', 'shop_api_amazon.shop_id=shop.id')
				->setColumns('shop_api_amazon.*, shop.id as shop_id, shop.name, shop.platform')
				->asArray()->getOne();
			$this->_view['shop'] = $shop;
		}
	}
	
	function actionAmazonTokenEditSave()
	{
		$this->_view['title'] = 'Amazon令牌修改（保存）';
		if (isset($_POST['shop_id']) && $_POST['shop_id'])
		{
			$result = Shop_Api_Amazon::AmazonTokenEdit($_POST);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirect($_SERVER['HTTP_REFERER']);
			}
		}
	}
	
	function actionNewsList()
	{
		$this->_view['title'] = '公告列表';
		$cp = isset($_GET['cp']) ? $_GET['cp'] : 0;
		$ps = isset($_GET['ps']) ? $_GET['ps'] : 10;
		$url_arr = Helper_BSS_Normal::buildCondition();
		$select = News::find()->joinLeft('user', 'user.name as user_name', 'user.id=news.user_id')->limitPage($cp, $ps);
		$news = $select->order('create_time desc')->asArray()->getAll();
		foreach ($news as $k => $n)
		{
			$news[$k]['unread'] = News_Unread::find('news_id=? and user_id=?', $n['id'], CURRENT_USER_ID)->asArray()->getOne();
		}
		$pagination = $select->getPagination();
		$page = new Helper_BSS_Page($pagination, url('Setting::Basic/NewsList'));
		$this->_view['page'] = $page->getPage();
		$this->_view['news'] = $news;
	}
	
	function actionNewsCreate()
	{
		$this->_view['title'] = '创建公告';
	}
	
	function actionNewsCreateSave()
	{
		$this->_view['title'] = '创建公告（保存）';
		if ($this->_context->isPOST())
		{
			$news = array();
			$news['title'] = trim($_POST['title']);
			$news['content'] = trim($_POST['content']);
			if ($news['title'] && $news['content'])
			{
				$result = News::create($news);
				if ($result['ack'] == SUCCESS)
				{
					return $this->_redirectMessage('发布成功', '正在返回..', url('Setting::Basic/NewsList'), $result['ack']);
				}
				else
				{
					return $this->_redirectMessage('发布失败', $result['message'], $_SERVER['HTTP_REFERER'], $result['ack']);
				}
			}
			else
			{
				return $this->_redirectMessage('发布失败', '标题或内容不能为空！', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
	}
	
	function actionNewsDetail()
	{
		$this->_view['title'] = '公告详细';
		if (isset($_REQUEST['news_id']))
		{
			$news = News_Unread::find('news_id=? and user_id=?', $_REQUEST['news_id'], CURRENT_USER_ID)->asArray()->getOne();
			if ($news)
			{
				News_Unread::meta()->deleteWhere('news_id=? and user_id=?', $news['news_id'], CURRENT_USER_ID);
				echo 1;exit;
			}
		}
		echo 0;exit;
	}
	
	function actionAliExpressTokenList()
	{
		$this->_view['title'] = '速卖通令牌列表';
		$shop = Shop::find('platform=? and status=1', 'aliexpress')
			->joinLeft('shop_api_aliexpress', 'key, secret, access_token, refresh_token, refresh_token_expire_time', 'shop_api_aliexpress.shop_id=shop.id')
			->asArray()->getAll();
		foreach ($shop as &$s)
		{
			$param = array(
				'client_id' => $s['key'],
				'redirect_uri' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['CONTEXT_PREFIX'] . '/aliexpress.php?shop_id=' . $s['id'],
				'site' => 'aliexpress'
			);
			ksort($param);
			$sign = '';
			$url = Q::ini('custom_api/aliexpress_auth_get_code_uri');
			foreach ($param as $key => $val)
			{
				if ($key != '' && $val != '')
				{
					$sign .= $key . $val;
					$url .= $key . '=' . $val . '&';
				}
			}
			$sign = strtoupper(bin2hex(hash_hmac("sha1", $sign, $s['secret'], true)));
			$url .= '_aop_signature=' . $sign;
			$s['auth_url'] = $url;
		}
		unset($s);
		$this->_view['shop'] = $shop;
	}
	
	function actionAliExpressTokenGet()
	{
		$this->_view['title'] = '速卖通令牌获取';
		if (! empty($_GET['shop_id']) && ! empty($_GET['code']))
		{
			$shop_api = Shop_API_AliExpress::find('shop_id=?', $_GET['shop_id'])->getOne();
			$url = Q::ini('custom_api/aliexpress_auth_get_token_uri') . $shop_api['key'];
			$param = array(
				'redirect_uri' => urlencode('http://' . $_SERVER['HTTP_HOST'] . url('Setting::Basic/AliExpressTokenSave', array('shop_id' => $_GET['shop_id']))),
				'grant_type' => 'authorization_code',
				'need_refresh_token' => 'true',
				'client_id' => $shop_api['key'],
				'client_secret' => $shop_api['secret'],
				'code' => $_GET['code']
			);
			$ret = Helper_BSS_API::AliExpressAPICall($url, $param);
			if (isset($ret['error']))
			{
				return $this->_redirectMessage('授权失败', $ret['error_description'] , url('Setting::Basic/AliExpressTokenList'), FAILURE);
			}
			$shop_api->access_token = $ret['access_token'];
			$shop_api->refresh_token = $ret['refresh_token'];
			$shop_api->last_refresh_time = CURRENT_DATETIME;
			$shop_api->refresh_token_expire_time = Helper_BSS_Normal::AliExpressDateTransfer($ret['refresh_token_timeout']);
			$shop_api->save();
			return $this->_redirectMessage('店铺授权成功', '正在返回列表..' , url('Setting::Basic/AliExpressTokenList'), SUCCESS);
		}
	}
	
	function actionShopAllotByuserSave()
	{
		$this->_view['title'] = '店铺分配（保存）';
		if (! empty($_POST['user_id']))
		{
			$shop_ids = isset($_POST['shop_ids']) ? $_POST['shop_ids'] : array();
			$result = Shop_User_Mapping::updateMapping($shop_ids, $_POST['user_id']);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('分配成功', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
			}
		}
		else
		{
			return $this->_redirectMessage('用户错误', '正在返回..', $_SERVER['HTTP_REFERER'], $result['ack']);
		}
	}
	
	function actionShippingMethodList()
	{
		$this->_view['title'] = '邮寄列表';
		$this->_view['warehouse'] = Warehouse::getActiveWarehouse();
		$url_arr = Helper_BSS_Normal::buildCondition();
		$result = Shipping_method::search($url_arr, 0 ,0);
		if ($result['ack'] == SUCCESS)
		{
			$shipping_method = $result['data'];
			$this->_view['shipping_method'] = $shipping_method;
		}
	}
	
	function actionShippingMethodCreate()
	{
		$this->_view['title'] = '邮寄新建';
		$this->_view['warehouse'] = Warehouse::getActiveWarehouse();
		if (isset($_GET['id']))
		{
			$this->_view['shipping_method'] = Shipping_Method::find('id=?', $_GET['id'])->asArray()->getOne();;
		}
	}
	
	function actionShippingMethodSave()
	{
		$this->_view['title'] = '邮寄保存';
		if ($this->_context->isPOST())
		{
			$shipping_method = Shipping_Method::find('id=?', $_POST['id'])->getOne();
			if (! $shipping_method['id'])
			{
				$check_name = Shipping_Method::find('name=?', trim($_POST['name']))->asArray()->getOne();
				$check_code = Shipping_Method::find('code=?', trim($_POST['code']))->asArray()->getOne();
				if ($check_name || $check_code)
				{
					return $this->_redirectMessage('填写的名称或代号已存在！', '正在返回..', $_SERVER['HTTP_REFERER'], FAILURE);
				}
			}
			$result = Shipping_Method::shippingMethodSave($_POST);
		}
		return $this->_redirect($_SERVER['HTTP_REFERER']);
	}
	
	function actionDeleteCache()
	{
		$this->_view['title'] = '清空缓存';
		$cache_path = Q::ini('app_config/CONFIG_CACHE_SETTINGS/QCache_File/cache_dir');
		$handle = opendir($cache_path); 
		if ($handle)
		{
			while (($file = readdir($handle)) != false)
			{
				if ($file != '.' && $file != '..' && $file != '.svn')
				{
					if (is_file($cache_path . '/' . $file) && substr($file, strrpos($file, '.') + 1) == 'php')
					{
						unlink($cache_path . '/' . $file);
					}
				}
			}
			closedir($handle);
			clearstatcache();
			return $this->_redirectMessage('清空缓存成功', '正在返回', $_SERVER['HTTP_REFERER'], SUCCESS);
		}
	}
	
	function actionShopAllotUser()
	{
		$this->_view['title'] = '店铺分配用户';
		$users = User::find('type!=1 and status=? and parent_id=?', Q::ini('custom_flag/user_status/on_duty/value'), CURRENT_USER_ID)->asArray()->getAll();
		if (isset($_GET['shop_id']) && $_GET['shop_id'])
		{
			$shop_user_mappings = Shop_User_Mapping::find('shop_id=?', $_GET['shop_id'])->asArray()->getAll();
			$shop_user_mapping = array();
			foreach ($shop_user_mappings as $sum)
			{
				$shop_user_mapping[] = $sum['user_id'];
			}
			$this->_view['shop_user_mapping'] = $shop_user_mapping;
			$this->_view['users'] = $users;
			$this->_view['shop_id'] = $_GET['shop_id'];
		}
		else
		{
			return $this->_redirectMessage('店铺不存在', '请返回重新刷新页面', '', FAILURE);
		}
	}
	
	function actionShopAllotUserSave()
	{
		$this->_view['title'] = '店铺分配用户（保存）';
		$shop = Shop::find('id=?', $_POST['shop_id'])->asArray()->getOne();
		if ($shop)
		{
			$user_ids = (isset($_POST['user_ids'])) ? $_POST['user_ids'] : array();
			$result = Shop_User_Mapping::updateShopAllotUserByShop($shop['id'], $user_ids);
			if ($result['ack'] == SUCCESS)
			{
				return $this->_redirectMessage('店铺分配用户成功', '正在返回', $_SERVER['HTTP_REFERER'], SUCCESS);
			}
			else
			{
				return $this->_redirecMessage('店铺分配用户失败', '请重新分配用户', $_SERVER['HTTP_REFERER'], FAILUER);
			}
		}
		else
		{
			return $this->_redirectMessage('店铺分配用户失败', '店铺不存在', $_SERVER['HTTP_REFERER'], FAILURE);
		}
	}
	
	function actionWishTokenList()
	{
		$this->_view['title'] = 'Wish令牌';
		$shop = Shop_User_Mapping::getShopByPlatform('wish');
		$arr = array();
		foreach ($shop as $key => $s)
		{
			$arr[$key] = Shop_API_Wish::find('shop_id=?', $s['id'])->asArray()->getOne();
			$arr[$key]['name'] = $s['name'];
		}
		$this->_view['shop'] = $arr;
	}
	
	function actionWishShopEdit()
	{
		$this->_view['title'] = 'Wish店铺（修改）';
		if (empty($_GET['id']) && empty($_GET['shopname'])) return $this->_redirectMessage('授权失败', '请求参数有误', $_SERVER['HTTP_REFERER'], FAILURE);
		$shop = Shop_API_Wish::find('id=?', $_GET['id'])->asArray()->getOne();
		$shop['name'] = $_GET['shopname'];
		$this->_view['shop'] = $shop;
	}
	
	function actionWishShopEditSave()
	{
		$this->_view['title'] = 'Wish店铺（修改保存）';
		
		if (empty($_POST['client_id']) || empty($_POST['client_secret']) || empty($_POST['redirect_uri']) || empty($_POST['id'])) return $this->_redirectMessage('更新失败', '请求参数有误', $_SERVER['HTTP_REFERER'], FAILURE);
		$data = array(
			'id' => (int)$_POST['id'],
			'client_id' => trim($_POST['client_id']),
			'client_secret' => trim($_POST['client_secret']),
			'redirect_uri' => trim($_POST['redirect_uri'])
		);
		Shop_API_Wish::meta()->updateDbWhere($data);
		return $this->_redirectMessage('更新成功', '正在跳转', $_SERVER['HTTP_REFERER'], SUCCESS);
	}
	
	function actionWishShopAuth()
	{
		$this->_view['title'] = 'Wish店铺授权';
		if (empty($_POST['id']) || empty($_POST['code'])) return $this->_redirectMessage('授权失败', '请求参数有误', $_SERVER['HTTP_REFERER'], FAILURE);
		$api = Shop_API_Wish::find('id=?', $_POST['id'])->asArray()->getOne();
		if (empty($api)) return $this->_redirectMessage('授权失败', '请求参数有误', $_SERVER['HTTP_REFERER'], FAILURE);
		$result = Shop_API_Wish::auth($api['client_id'], $api['client_secret'], $_POST['code'], $api['redirect_uri']);
		if ($result['ack'] == SUCCESS) return $this->_redirectMessage('授权成功', '正在跳转', url('Setting::Basic/WishTokenList'));
		return $this->_redirectMessage('授权失败', $result['message'], url('Setting::Basic/WishTokenList'));
	}
}
